package au.org.nh.dao.hsqldb.impl;

import java.util.Collection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import au.org.nh.dao.HibernateUtil;
import au.org.nh.dao.PatientInfo;
import au.org.nh.dao.PatientInfoDAO;
import au.org.nh.dao.mongo.impl.DBException;

public class HSQLDBPatientInfoDAOImpl implements PatientInfoDAO {

	@Override
	public void save(final PatientInfo info) throws DBException {
		final SessionFactory factory = HibernateUtil.getSessionFactory();
		final Session session = factory.openSession();
		final Transaction transaction = session.beginTransaction();
		session.save(info);
		transaction.commit();
		session.flush();
		session.close();
	}

	@Override
	public PatientInfo get(final String name) throws DBException {
		PatientInfo info = null;
		final Session session = HibernateUtil.getSessionFactory().openSession();
		final Query query = session
				.createQuery("from PatientInfo where firstName = :inputName ");
		query.setParameter("inputName", name);
		final List<PatientInfo> infoList = query.list();
		System.out.println("Size of list is " + infoList.size());
		if (infoList != null && infoList.size() > 0) {
			info = infoList.get(0);
		}
		session.close();
		return info;
	}

	@Override
	public Collection<PatientInfo> getAll() {
		final Session session = HibernateUtil.getSessionFactory().openSession();
		final Query query = session.createQuery("from PatientInfo");
		return query.list();
	}

	@Override
	public PatientInfo getById(final Long inputId) throws DBException {
		PatientInfo info = null;
		final Session session = HibernateUtil.getSessionFactory().openSession();
		final Query query = session
				.createQuery("from PatientInfo where id = :inputId ");
		query.setParameter("inputId", inputId);
		final List<PatientInfo> infoList = query.list();
		System.out.println("Size of list is " + infoList.size());
		if (infoList != null && infoList.size() > 0) {
			info = infoList.get(0);
		}
		session.close();
		System.out.println("Patient info " + info);
		return info;
	}

}
